package com.epro.dx.widget;

import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 图片浏览控件
 * @author chenxiaolei/sai`kopui
 * @id nj728
 * 神一般的存在..
 */
public class ProductImageBrowseView extends View
{
    /**
     * 左缩放
     */
    private Matrix matrixLeft = new Matrix();
    
    /**
     * 右缩放
     */
    private Matrix matrixRight = new Matrix();
    
    /**
     * 是否是从右往左拖
     */
    private boolean isRight2Left = true;
    
    /**
     * 产品图片列表
     */
    private String[] largeImageLargeUrlArray;
    
    /**
     * 产品图片列表
     */
    private HashMap<String, Bitmap> bitmapMap = new HashMap<String, Bitmap>();
    
    /**
     * 当前图片索引
     */
    private int currentPicIndex = 0;
    
    /**
     * 目标图片索引
     */
    private int targetPicIndex;
    
    /**
     * 手持的偏移量
     */
    private float excursion = 0;
    
    /**
     * 左边边界高度的偏移量
     */
    private int borderExcursionLeft = 0;
    
    /**
     * 右边边界高度的偏移量
     */
    private int borderExcursionRight = 0;
    
    /**
     * 两边每次的缩进量
     */
    private float borderIndent = 0;
    
    /**
     * 是否移动结束
     */
    private boolean isMoveOver = true;
    
    /**
     * 是否开始拖动
     */
    private boolean canMove = false;
    
    /**
     * 开始坐标
     */
    private float startX = -1;
    
    /**
     * . 上一次的坐标
     */
    private float lastX = -1;
    
    /**
     * 中间图片
     */
    private Bitmap bitMid;
    
    /**
     * 左边图片
     */
    private Bitmap bitLeft;
    
    /**
     * 右边图片
     */
    private Bitmap bitRight;
    
    /**
     * 回调引用
     */
    private onPicIndexChangeListener listener;
    
    /**
     * 构造
     *
     * @param context
     *            上下文对象
     * @param productModel
     *            产品Model对象
     */
    public ProductImageBrowseView(Context context)
    {
        super(context);
    }
    
    public ProductImageBrowseView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }
    
    public ProductImageBrowseView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }
    
    /**
     * 设置产品数据源
     *
     * @param model
     *            产品对象
     */
    public void setProductDataSource(HashMap<String, Bitmap> bitmapMap, String[] largeImgUrl)
    {
        setProductDataSource(bitmapMap, largeImgUrl, 0);
    }
    
    /**
     * 设置产品数据源
     * @param bitmapMap 图片对象数组
     * @param largeImgUrl 图片对象的网络地址数组
     * @param index 当前期望的索引
     */
    public void setProductDataSource(HashMap<String, Bitmap> bitmapMap, String[] largeImgUrl, int index)
    {
        if (bitmapMap != null && !bitmapMap.isEmpty())
        {
            this.bitmapMap = bitmapMap;
            this.largeImageLargeUrlArray = largeImgUrl;
            if (index >= 0)
            {
                currentPicIndex = index;
            }
            invalidate();
        }
    }
    
    /**
     * 绘制图片
     */
    private void drawBitmap(Canvas canvas, float src[], float dst[], Bitmap bit, Matrix matrix)
    {
        canvas.save();
        
        matrix.setPolyToPoly(src, 0, dst, 0, src.length >> 1);
        
        canvas.concat(matrix);
        
        canvas.drawBitmap(bit, 0, 0, null);
        
        canvas.restore();
    }
    
    /**
     * 将图片绘制到画布上
     */
    private void drawBitmap2Canvas(Canvas canvas)
    {
        // 左图原始坐标矩阵
        float[] leftSrcPostion;
        
        // 右图原始坐标矩阵
        float[] rightSrcPostion;
        
        // 左图目标坐标矩阵
        float[] leftdstPostion;
        
        // 右图目标坐标矩阵
        float[] rightdstPostion;
        
        // 松手了，拖动结束或者是第一次进入
        if (isMoveOver)
        {
            Matrix matrix = new Matrix();
            
            Bitmap bit = getBitFromMap(largeImageLargeUrlArray[currentPicIndex]);
            
            leftSrcPostion = new float[] {0, 0, bit.getWidth(), 0, bit.getWidth(), bit.getHeight(), 0, bit.getHeight()};
            
            leftdstPostion = new float[] {0, 0, getWidth(), 0, getWidth(), getHeight(), 0, getHeight()};
            
            canvas.save();
            
            matrix.setPolyToPoly(leftSrcPostion, 0, leftdstPostion, 0, leftSrcPostion.length >> 1);
            
            canvas.concat(matrix);
            
            canvas.drawBitmap(bit, 0, 0, null);
            
            canvas.restore();
        }
        // 是从右往左拖
        else if (isRight2Left)
        {
            //计算目标页数，就是右边那张图片的索引
            targetPicIndex = calcIndex(currentPicIndex + 1);
            
            //中间展示的图片对象
            bitMid = getBitFromMap(largeImageLargeUrlArray[currentPicIndex]);
            
            //右边展示的图片对象
            bitRight = getBitFromMap(largeImageLargeUrlArray[targetPicIndex]);
            
            // 中间
            leftSrcPostion =
                new float[] {0, 0, bitMid.getWidth(), 0, bitMid.getWidth(), bitMid.getHeight(), 0, bitMid.getHeight()};
            leftdstPostion =
                new float[] {borderIndent, borderExcursionLeft, getWidth() - excursion, 0, getWidth() - excursion,
                    getHeight(), borderIndent, getHeight() - borderExcursionLeft};
            
            // 右边
            rightSrcPostion =
                new float[] {0, 0, bitRight.getWidth(), 0, bitRight.getWidth(), bitRight.getHeight(), 0,
                    bitRight.getHeight()};
            
            rightdstPostion =
                new float[] {getWidth() - excursion, 0, getWidth() - borderIndent, borderExcursionRight,
                    getWidth() - borderIndent, getHeight() - borderExcursionRight, getWidth() - excursion, getHeight()};
            
            drawBitmap(canvas, leftSrcPostion, leftdstPostion, bitMid, matrixLeft);
            
            drawBitmap(canvas, rightSrcPostion, rightdstPostion, bitRight, matrixRight);
        }
        // 从左往右拖
        else
        {
            //计算目标页数，就是左边那张图片的索引
            targetPicIndex = calcIndex(currentPicIndex - 1);
            
            //左边展示的图片对象
            bitLeft = getBitFromMap(largeImageLargeUrlArray[targetPicIndex]);
            
            //中间展示的图片对象
            bitMid = getBitFromMap(largeImageLargeUrlArray[currentPicIndex]);
            
            // 左边
            leftSrcPostion =
                new float[] {0, 0, bitLeft.getWidth(), 0, bitLeft.getWidth(), bitLeft.getHeight(), 0,
                    bitLeft.getHeight()};
            leftdstPostion =
                new float[] {borderIndent, borderExcursionLeft, excursion, 0, excursion, getHeight(), borderIndent,
                    getHeight() - borderExcursionLeft};
            
            // 中间
            rightSrcPostion =
                new float[] {0, 0, bitMid.getWidth(), 0, bitMid.getWidth(), bitMid.getHeight(), 0, bitMid.getHeight()};
            
            rightdstPostion =
                new float[] {excursion, 0, getWidth() - borderIndent, borderExcursionRight, getWidth() - borderIndent,
                    getHeight() - borderExcursionRight, excursion, getHeight()};
            
            drawBitmap(canvas, leftSrcPostion, leftdstPostion, bitLeft, matrixLeft);
            
            drawBitmap(canvas, rightSrcPostion, rightdstPostion, bitMid, matrixRight);
        }
    }
    
    /**
     * 根据地址获取图片
     */
    private Bitmap getBitFromMap(String imageUrl)
    {
        Bitmap bit = bitmapMap.get(imageUrl);
        
        if (bit == null)
        {
            bit = bitmapMap.get("default");
        }
        
        return bit;
    }
    
    /**
     * 将图片画在画布上，用于展示
     */
    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);
        
        if (largeImageLargeUrlArray == null || largeImageLargeUrlArray.length == 0)
        {
            return;
        }
        
        canvas.save();
        drawBitmap2Canvas(canvas);
        canvas.restore();
    }
    
    /**
     * 拖动
     */
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        int userAction = event.getAction();
        
        // 按下
        if (userAction == MotionEvent.ACTION_DOWN)
        {
            // 获取手指按下的坐标
            startX = event.getX();
            // 初始化将按下的坐标作为上一次点击的坐标
            lastX = startX;
            //左右X轴缩进量
            borderIndent = 10;
        }
        // 移动
        else if (userAction == MotionEvent.ACTION_MOVE)
        {
            // 位移大于40才允许移动画面
            if (!canMove && Math.abs(event.getX() - startX) > 40)
            {
                // 如果大于40了就开启拖动
                canMove = true;
                // 如果是动了的话那么移动就是没有结束
                isMoveOver = false;
                
                if (event.getX() - startX < 0)
                {
                    isRight2Left = true;
                    borderExcursionLeft = 10;
                    borderExcursionRight = 40;
                }
                else
                {
                    isRight2Left = false;
                    borderExcursionLeft = 40;
                    borderExcursionRight = 10;
                }
                
            }
            
            // 启动，要绘图了
            if (canMove)
            {
                // 是往左拖的
                if (event.getX() - lastX < 0)
                {
                    //手指触摸的X坐标到达了矩阵的左边界，就是屏幕上看到的那个正方型的最右边
                    //                    if (event.getX() <= borderIndent)
                    //                    {
                    //
                    //                    }
                    // 往右
                    if (lastX < event.getX())
                    {
                        excursion = Math.abs(startX - event.getX());
                        borderExcursionLeft -= 1;
                        borderExcursionRight += 1;
                        borderIndent += 0.1;
                    }
                    else
                    {
                        excursion = Math.abs(startX - event.getX());
                        borderExcursionLeft += 1;
                        borderExcursionRight -= 1;
                        borderIndent -= 0.1;
                    }
                }
                // 从左向右拖
                else
                {
                    //手指触摸的X坐标到达了矩阵的右边界，就是屏幕上看到的那个正方型的最右边
                    if (event.getX() >= getWidth() - borderIndent)
                    {
                        
                    }
                    // 往左
                    else if (lastX > event.getX())
                    {
                        excursion = Math.abs(startX - event.getX());
                        borderExcursionLeft += 1;
                        borderExcursionRight -= 1;
                        borderIndent += 0.1;
                    }
                    // 往右
                    else
                    {
                        excursion = Math.abs(startX - event.getX());
                        borderExcursionLeft -= 1;
                        borderExcursionRight += 1;
                        borderIndent -= 0.1;
                    }
                }
                lastX = event.getX();
                //参数设置完毕，重构页面视图
                invalidate();
            }
        }
        // 放开
        else if (userAction == MotionEvent.ACTION_UP)
        {
            //如果过半，那么就要将中间的图片切换为上一张或者下一张
            if (isRight2Left && (int)Math.abs(lastX - startX) > getWidth() / 2)
            {
                nextImg();
                if (listener != null)
                {
                    listener.onPicIndexChange(currentPicIndex);
                }
            }
            else if (!isRight2Left && (int)Math.abs(lastX - startX) > getWidth() / 2)
            {
                preImg();
                if (listener != null)
                {
                    listener.onPicIndexChange(currentPicIndex);
                }
            }
            
            canMove = false;
            isRight2Left = true;
            excursion = 0;
            borderExcursionLeft = 0;
            borderIndent = 0;
            isMoveOver = true;
        }
        invalidate();
        return true;
    }
    
    /**
     * 下一张图片索引
     */
    public int nextImg()
    {
        currentPicIndex = calcIndex(currentPicIndex + 1);
        return currentPicIndex;
    }
    
    /**
     * 前一张图片索引
     */
    public int preImg()
    {
        currentPicIndex = calcIndex(currentPicIndex - 1);
        return currentPicIndex;
    }
    
    /**
     * 边界计算
     * @param index 索引
     * @return 索引
     */
    private int calcIndex(int index)
    {
        //大于右边界，设置为0
        if (index > largeImageLargeUrlArray.length - 1)
        {
            index = 0;
        }
        //小于左边界，设置为右边界
        else if (index < 0)
        {
            index = largeImageLargeUrlArray.length - 1;
        }
        return index;
    }
    
    /**
     * 根据索引得到图片
     * @param index 索引
     */
    public void getImage(int index)
    {
        currentPicIndex = calcIndex(index);
        invalidate();
    }
    
    /**
     * 回调接口
     * @author chenxiaolei/saikopui
     * @id nj728
     */
    public interface onPicIndexChangeListener
    {
        public void onPicIndexChange(int picIndex);
    }
    
    public void onPicIndexChangeListener(onPicIndexChangeListener listener)
    {
        this.listener = listener;
    }
    
}
